package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.model.OrderMessage;
import net.xdclass.service.ProductOrderService;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

/**
 * 小滴课堂,愿景：让技术不再难学
 *
 * @Description
 * @Author 二当家小D
 * @Remark 有问题直接联系我，源码-笔记-技术交流群
 * @Version 1.0
 **/

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.order_close_queue}")
public class ProductOrderMQListener {

    @Autowired
    private ProductOrderService productOrderService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final int MAX_RETRY = 3;

    @RabbitHandler
    public void closeProductOrder(OrderMessage orderMessage,Message message,Channel channel) throws IOException {

        log.info("监听到消息:{}",orderMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();

        try {

            boolean flag = productOrderService.closeProductOrder(orderMessage);
            if (flag){
                channel.basicAck(msgTag,false);
            } else {
                channel.basicReject(msgTag,true);
            }
        } catch (IOException e){
            log.error("定时关单失败:{}",e);
            channel.basicReject(msgTag,true);
        }


    }



//    @RabbitHandler
//    public void releaseCouponRecord(CouponRecordMessage recordMessage, Message message, Channel channel) throws IOException {
//
//        log.info("监听到消息：releaseCouponRecord消息内容：{}", recordMessage);
//        long msgTag = message.getMessageProperties().getDeliveryTag();
//
//        boolean flag = couponRecordService.releaseCouponRecord(recordMessage);
//
//        String retryKey = "retry:coupon_record_release:"+recordMessage.getTaskId();
//        redisTemplate.opsForValue().setIfAbsent(retryKey,"1");
//
//        //防止同个解锁任务并发进入；如果是串行消费不用加锁；加锁有利也有弊，看项目业务逻辑而定
//        Lock lock = redissonClient.getLock("lock:coupon_record_release:"+recordMessage.getTaskId());
//        lock.lock();
//        try {
//            if (flag) {
//                //确认消息消费成功
//                channel.basicAck(msgTag, false);
//            }else {
//                int retryTime = Integer.parseInt((String)redisTemplate.opsForValue().get(retryKey));
//                if (retryTime >= MAX_RETRY){
//                    channel.basicAck(msgTag,false);
//                    //TODO 添加记录到数据库
//                    log.info("人工核查");
//                } else {
//                    log.error("释放优惠券失败 flag=false,{}",recordMessage);
//                    channel.basicReject(msgTag,true);
//                    redisTemplate.opsForValue().set(retryKey,String.valueOf(retryTime+1));
//                }
//            }
//
//        } catch (IOException e) {
//            int retryTime = Integer.parseInt((String)redisTemplate.opsForValue().get(retryKey));
//            if (retryTime >= MAX_RETRY){
//                channel.basicAck(msgTag,false);
//                //TODO 添加记录到数据库
//                log.info("人工核查");
//            } else {
//                log.error("释放优惠券记录异常:{},msg:{}",e,recordMessage);
//                channel.basicReject(msgTag,true);
//                redisTemplate.opsForValue().set(retryKey,String.valueOf(retryTime+1));
//            }
//        }
//        finally {
//            lock.unlock();
//        }
//
//
//    }


    @RabbitHandler
    public void releaseCouponRecord2(String msg,Message message, Channel channel) throws IOException {

        log.info(msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
    }

}
